<?php

namespace App\Repositories;

use App\Entities\AdminCity;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Support\Facades\Hash;
use App\Repositories\UserRepository;
use App\Entities\User;
use App\Entities\RoleUser;
use App\Validators\UserValidator;

/**
 * Class UserRepositoryEloquent.
 *
 * @package namespace LayuiAdmin\Repositories;
 */
class UserRepositoryEloquent extends BaseRepository implements UserRepository
{
    public function create(array $data)
    {
        $data['password'] = Hash::make($data['password']);
        return parent::create($data);
    }

    public function createDefault($username, $password, $mobile)
    {
        $this->model->truncate();
        $data = [];
        $data['name'] = $username;
        $data['email'] = '';
        $data['mobile'] = $mobile;
        $data['password'] = Hash::make($password);
        $data['is_super'] = 1;
        return parent::create($data);
    }

    public function update(array $data, $id)
    {
        if (!empty($data)) {
            $data['password'] = Hash::make($data['password']);
        }
        return parent::update($data, $id);
    }

    public function relate(array $data, $id)
    {
        RoleUser::where('user_id', $id)->delete();
        $created = true;
        foreach ($data['roles'] as $role_id) {
            if (!RoleUser::create(['role_id' => $role_id, 'user_id' => $id])) {
                $created = false;
            }
        }
        return $created;
    }

    public function related($id)
    {
        return RoleUser::where('user_id', $id)->get();
    }

    public function cities($id)
    {
        return AdminCity::where('user_id', $id)->get();
    }

    public function resetPassword($id, $repassword)
    {
        return User::where('id', $id)->update(['password' => Hash::make($repassword)]);
    }

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return User::class;
    }



    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

}
